package com.eckey.lab.service.impl;

import com.alibaba.fastjson.JSON;
import com.eckey.lab.entity.Storage;
import com.eckey.lab.dao.StorageDao;
import com.eckey.lab.service.StorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;

/**
 * (Storage)表服务实现类
 *
 * @author makejava
 * @since 2023-09-24 15:44:16
 */
@Slf4j
@Service("storageService")
public class StorageServiceImpl implements StorageService {

    @Resource
    private StorageDao storageDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    public Storage queryById(Integer id) {
        return this.storageDao.queryById(id);
    }

    /**
     * 新增数据
     *
     * @param storage 实例对象
     * @return 实例对象
     */
    public Storage insert(Storage storage) {
        this.storageDao.insert(storage);
        return storage;
    }

    /**
     * 修改数据
     *
     * @param storage 实例对象
     * @return 实例对象
     */
    public Storage update(Storage storage) {
        this.storageDao.update(storage);
        return this.queryById(storage.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    public boolean deleteById(Integer id) {
        return this.storageDao.deleteById(id) > 0;
    }

    public boolean deduct(String productName, Integer totalNum) {
        Storage storage = storageDao.queryByName(productName);
        if (storage.getProductNum() >= totalNum) {
            storage.setProductNum(storage.getProductNum() - totalNum);
            storageDao.update(storage);
            log.info("更新storage:{}", JSON.toJSONString(storage));
            return true;
        } else {
            throw new RuntimeException("库存不够");
        }

    }
}
